package com.cheerful.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheerful.blog.dao.ArticleDao;
import com.cheerful.blog.entity.Article;
import com.cheerful.blog.entity.Category;
import com.cheerful.blog.entity.Comment;
import com.cheerful.blog.service.ArticleService;
import com.cheerful.blog.service.CategoryService;
import com.cheerful.blog.service.CommentService;
import com.cheerful.blog.to.ArchiveVo;
import com.cheerful.blog.to.ArticleVo;
import com.cheerful.blog.util.ConvertUtil;
import com.cheerful.blog.util.QiniuOssUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * (Article)表服务实现类
 *
 * @author makejava
 * @since 2022-02-07 13:15:03
 */
@Service("articleService")
public class ArticleServiceImpl extends ServiceImpl<ArticleDao, Article> implements ArticleService {
    @Autowired
    CategoryService categoryService;

    @Autowired
    CommentService commentService;

    @Override
    public ArticleVo getArticleDetail(Long id) {
        ArticleVo articleVo = new ArticleVo();
        Article article = this.getById(id);
        //将md代码转换为html代码发给前端
        String html = ConvertUtil.markdownToHtmlExtensitons(article.getContent());
        article.setContent(html);
        BeanUtils.copyProperties(article,articleVo);
        String categoryList = article.getCategoryList();
        //获取文章的分类
        List<String> tags = Arrays.stream(categoryList.split(":")).map(item -> {
            Category category = categoryService.getById(item);
            return category.getCategoryName();
        }).collect(Collectors.toList());
        articleVo.setTags(tags);
        //获取文章下的评论
        List<Comment> comments=commentService.listForArticle(id);
        articleVo.setComments(comments);
        return articleVo;
    }

    @Override
    public List<Article> getArticleByCategory(Long categoryId) {
        List<Article> articles = this.list();
        for (int i = 0; i < articles.size(); i++) {
            Article item = articles.get(i);
            String s = item.getCategoryList();
            String[] split = s.split(":");
            List<String> list = Arrays.asList(split);
            if (!list.contains(categoryId.toString())){
                articles.remove(item);
                i--;
                continue;
            }
            List<String> categoryNameList = list.stream().map(category -> {
                Category categoryEntity = categoryService.getById(category);
                return categoryEntity.getCategoryName();
            }).collect(Collectors.toList());
            item.setCategoryNameList(categoryNameList);
        }
        return articles;
    }

    @Override
    public Integer countCategory(Long categoryId) {
        int res=0;
        List<Article> articles = this.list();
        for (Article article : articles) {
            String categoryList = article.getCategoryList();
            List<String> list = Arrays.asList(categoryList.split(":"));
            if (list.contains(categoryId.toString())) {
                res++;
            }
        }
        return res;
    }

    @Override
    public Page<ArticleVo> pageWithDetail(Page<Article> page, QueryWrapper<Article> articleQueryWrapper) {
        Page<Article> articleList = this.page(page, articleQueryWrapper);
        List<ArticleVo> collect = articleList.getRecords().stream().map(item ->
                this.getArticleDetail(item.getId())
        ).collect(Collectors.toList());
        Page<ArticleVo> result= new Page<>(page.getCurrent(),page.getSize(),page.getTotal());
        result.setRecords(collect);
        return result;
    }

    @Override
    public List<Article> getHotArticles() {
        return this.baseMapper.getHotArticles();
    }

    @Override
    public void updateViewNums(Long id, Integer viewNums) {
        this.baseMapper.updateViewNums(id,viewNums);
    }

    @Override
    public List<ArchiveVo> getArticlesGroupByYearMonth() {
        List<ArchiveVo> group = this.baseMapper.getGroupByYearMonth();
        group.forEach(item->{
            List<Article> info=this.baseMapper.getGroupInfo(item.getYearNum(),item.getMonthNum());
            item.setArticleList(info);
        });
        return group;
    }

    @Override
    public Article addArticle(MultipartFile picture, MultipartFile mdFile, String title, String blogDesc, String categoryList) throws IOException {
        String cover = QiniuOssUtil.upload(picture, "wzf-image-blog");
        String content=getContent(mdFile);
        Article article = new Article();
        article.setCategoryList(categoryList);
        article.setTitle(title);
        article.setCoverId(cover);
        article.setContent(content);
        article.setBlogDesc(blogDesc);
        article.setAuthorName("cheerful");
        return this.save(article)?article:null;
    }

    public String getContent(MultipartFile file) throws IOException {
        //起手转成字符流
        StringBuilder res= new StringBuilder();
        InputStream is = file.getInputStream();
        InputStreamReader isReader = new InputStreamReader(is, StandardCharsets.UTF_8);
        BufferedReader br = new BufferedReader(isReader);
        //循环逐行读取
        while (br.ready()) {
            res.append(br.readLine()).append("\r\n");
        }
        //关闭流，讲究
        br.close();
        return res.toString();
    }
}

